package util

import (
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"io"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"time"
)

func newFileWriter(logName string, maxRemainCnt uint) (io.Writer, error) {
	writer, err := rotatelogs.New(
		logName+".%Y%m%d%H",
		rotatelogs.WithLinkName(logName),
		rotatelogs.WithRotationTime(time.Hour),
		rotatelogs.WithRotationCount(maxRemainCnt),
	)
	if err != nil {
		return nil, err
	}
	return writer, nil
}

func newConsoleWriter() io.Writer {
	return os.Stdout
}
func newLfsHook(writer io.Writer, useColor bool) logrus.Hook {
	format := CustomFormatter{
		logrus.TextFormatter{
			DisableColors:   false,
			FullTimestamp:   true,
			TimestampFormat: "2006-01-02 15:04:05",
			CallerPrettyfier: func(f *runtime.Frame) (string, string) {
				filename := filepath.Base(f.File)
				return "", filename + ":" + strconv.Itoa(f.Line)
			},
		},
		useColor,
	}

	lfsHook := lfshook.NewHook(lfshook.WriterMap{
		logrus.DebugLevel: writer,
		logrus.InfoLevel:  writer,
		logrus.WarnLevel:  writer,
		logrus.ErrorLevel: writer,
		logrus.FatalLevel: writer,
		logrus.PanicLevel: writer,
	}, &format)

	return lfsHook
}

func LogConfig() {
	fileWriter, err := newFileWriter("./logs/app.log", 1000)
	if err != nil {
		logrus.Errorf("failed to create file writer: %v", err)
		return
	}

	consoleWriter := newConsoleWriter()

	fileHook := newLfsHook(fileWriter, false)
	consoleHook := newLfsHook(consoleWriter, true)
	logrus.SetLevel(logrus.InfoLevel)
	logrus.SetReportCaller(true)
	logrus.AddHook(fileHook)
	logrus.AddHook(consoleHook)
}
